package com.rgp.apidriver.service.impl;

import com.rgp.apidriver.feign.ServiceDriverUserClient;
import com.rgp.apidriver.feign.ServiceVerificationcodeClient;
import com.rgp.apidriver.service.DriverUserLoginService;
import com.rgp.internalcommon.common.*;
import com.rgp.internalcommon.dto.ResponseResult;
import com.rgp.internalcommon.dto.VerificationCodeDto;
import com.rgp.internalcommon.response.DriverVerificationResponse;
import com.rgp.internalcommon.response.NumberCodeResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * @author nhp
 * @version 1.0
 * @description TODO
 * @date 2024-04-17 17:57
 */
@Service
public class DriverUserLoginServiceImpl implements DriverUserLoginService {

    @Autowired
    private ServiceDriverUserClient serviceDriverUserClient;

    @Autowired
    private ServiceVerificationcodeClient serviceVerificationcodeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult verificationCode(VerificationCodeDto verificationCodeDto) {

        String userPhone = verificationCodeDto.getUserPhone();

        //1.查询司机用户的手机号是否存在于db
        // 与业务逻辑有关，公司不提供开放的司机注册接口，司机必须通过公司的招聘后，才能在api-boss上完成对应的注册
        ResponseResult<DriverVerificationResponse> responseResult = serviceDriverUserClient.getDriverByPhoneNum(userPhone);
        Integer isExists = responseResult.getData().getIsExists();
        if (isExists.equals(DriverVerificationConstant.NOT_EXIST)){
            //若不在，则不发送相关的验证码，直接返回
            return ResponseResult.fail(CommonStatusEnum.DRIVER_USER_NOT_EXIST_ERROR);
        }

        //若在，则进入下一步流程，发送验证码
        //2.生成验证码
        ResponseResult<NumberCodeResponse> numberCode = serviceVerificationcodeClient.generateNumberCode(VerificationCodeConstant.VERIFICATION_CODE_SIZE);
        Integer verificationCode = numberCode.getData().getNumberCode();

        //3.验证码存入到redis
        stringRedisTemplate.opsForValue().set(RedisPrefixConstant.DRIVER_VERIFICATIONCODE_PREFIX + userPhone,verificationCode.toString(),VerificationCodeConstant.VERIFICATION_CODE_REDIS_TIME, TimeUnit.MINUTES);

        //4.发送验证码
        System.out.println("请求第三方服务向司机发送验证码");

        return ResponseResult.success();
    }
}